package com.bosssoft.hr.train.jsp.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.bosssoft.hr.train.jsp.example.exception.BusinessException;
import com.bosssoft.hr.train.jsp.example.pojo.User;
import com.bosssoft.hr.train.jsp.example.service.impl.UserServiceImpl;
import com.bosssoft.hr.train.jsp.example.service.UserService;
import com.bosssoft.hr.train.jsp.example.util.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**service
 * @param
 * @description:
 * @author: Administrator
 * @create: 2020-05-30 11:21
 * @since
 **/
@Slf4j
public class AddUserController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doPost(req,resp);
        }catch (ServletException | IOException e){
            log.error(e.getMessage());
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            JSONObject userJson = JSONUtil.getJson(req);
            User user = new User();
            if (userJson!=null){

                user.setName(userJson.getString("name"));
                user.setPassword(userJson.getString("password"));
                user.setId(Long.parseLong(userJson.getString("id")));
                user.setCode(userJson.getString("code"));
            }

            log.info(user.toString());

            boolean isSuccess = save(user);

            JSONObject object = new JSONObject();
            object.put("isSuccess",isSuccess);
            JSONUtil.writeJson(resp,object);


        }catch (NumberFormatException | IOException e){
            log.error(e.getMessage());
        }



    }

    private boolean save(User user){
        UserService userService = new UserServiceImpl();

        try {
            return userService.save(user);
        }catch (BusinessException e){
            log.error(e.getLocalizedMessage());
        }
        return false;
    }


}
